package com.example.demo.api;

import com.example.demo.common.AjaxResult;
import com.example.demo.common.UserSessionUtils;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserAPI {
    @Resource
    private UserService userService;

    @RequestMapping("/login")
    @ResponseBody
    public AjaxResult login(HttpServletRequest request,String username, String password) {
        if(!StringUtils.hasLength(username) || !StringUtils.hasLength(password)) {
            return AjaxResult.fail(-1,"非法请求！");
        }
        User user = userService.getUserByName(username);
        if(user != null && user.getUserId() > 0) {
            if(user.getPassword().equals(password)) {
                user.setPassword("");
                HttpSession session =request.getSession(true);
                session.setAttribute("USER_SESSION_KEY",user);
                return AjaxResult.success(user);
            }

        }
        return AjaxResult.success(0,null);
    }

    @RequestMapping("register")
    @ResponseBody
    public AjaxResult register(User user) {
        if(user == null || !StringUtils.hasLength(user.getUsername())
                || !StringUtils.hasLength(user.getPassword())) {
            return AjaxResult.fail(-1,"非法参数！");
        }

        return AjaxResult.success(userService.register(user));
    }
    @RequestMapping("userinfo")
    @ResponseBody
    public AjaxResult getUserInfo(HttpServletRequest request) {
        if(UserSessionUtils.getUserSession(request) == null) {
            return AjaxResult.fail(-1,"非法请求！");
        }
        return AjaxResult.success(userService.getUserByName(UserSessionUtils.getUserSession(request).getUsername()));
    }
}
